/* 
 * File:   lacoWhile.cpp
 * Author: Henrique
 * 
 * Created on 22 de Abril de 2010, 22:05
 */

#include "lacoWhile.h"
#include "atribuicao.h"
#include "Interpretador.h"

lacoWhile::lacoWhile() {
}

lacoWhile::lacoWhile(const lacoWhile& orig) {
}

lacoWhile::lacoWhile(std::string str, double* mem, std::vector<std::string> programa) {
    for (int i = 0; i < 26; i++) {
        this->memoria[i] = mem[i];
    }
    std::string temp;
    std::vector<std::string> comandos;
    int co = 0;
    int pilha = 0;
    for (int i = 0; i < programa.size(); i++) {

        char ch = str.at(str.size() - 1);
        while (ch == ' ' || ch == '\r') {
            str.erase(str.size() - 1, 1);
            ch = str.at(str.size() - 1);

        }
        ch = programa.at(i).at(programa.at(i).size() - 1);
        while (ch == ' ' || ch == '\r') {
            programa.at(i).erase(programa.at(i).size() - 1, 1);
            ch = programa.at(i).at(programa.at(i).size() - 1);

        }
        if (str.compare(programa.at(i)) == 0)
            co = 1;
        if (co == 1) {

            comandos.push_back(programa.at(i));

            if (programa.at(i).find("while") == 0 && !(programa.at(i).compare("endw") == 0)) {
                pilha++;
            } else
                if (programa.at(i).find("endw") == 0) {
                pilha--;
            }
            if (pilha == 0)
                break;

        }
    }

    for (int i = 0; i < str.size(); i++) {
        char c = str.at(i);
        if (c != ' ') {
            temp.append(1, c);
        }
    }

    this->listaDeComandos= comandos;
    for (int i = 0; i < str.size(); i++) {
        char ch = str.at(i);
        if(ch == ' '){
            str.erase(i,1);i--;
        }
    }
    this->condicional = str.substr(6,str.size()-7);
}

lacoWhile::~lacoWhile() {
}

double* lacoWhile::execute(){


    atribuicao *atrib = new atribuicao();
    while(atrib->processamentoAtribuicao(condicional)==(true || 1))
    {
        Interpretador *inter = new Interpretador();
        this->memoria = inter->execute(listaDeComandos,memoria);
    }

    return this->memoria;
}